import { backFunc, cellPhone, error, linkToEasy, modal, openLocation, toast } from '@/common/fun'
import Storage from '@/common/Storage'
import { checkIsLogin, getDomain, toGoodsDetail } from '@/common/helper'
import { arScanForflower } from '@/api'
import { Exception } from '@/common/Exception'
import store from '@/store'

export const pageMixin = {
  mixins: [], // 启用统计
  data () {
    return {
      JSSDK_READY: false,
      JSSDK_INIT: false, // 是否需要微信签名
      systemInfo: {
        statusBarHeight: 0,
        windowHeight: 0
      },
      diyHeadHeight: 0,
      diyHeadRight: 0,
      menuButtonInfo: {
        height: 0
      },
      TT: {}
    }
  },
  computed: {
  },
  methods: {
    getRect (selector, all) {
      return new Promise((resolve) => {
        uni.createSelectorQuery()
          .in(this)
          [all ? 'selectAll' : 'select'](selector)
          .boundingClientRect((rect) => {
            if (all && Array.isArray(rect) && rect.length) {
              resolve(rect)
            }

            if (!all && rect) {
              resolve(rect)
            }
          })
          .exec()
      })
    },
    $copy (str, tip = '已经复制到剪切板') {
      uni.setClipboardData({
        data: String(str),
        success () {
          toast(tip, 'none')
        }
      })
    },
    $toVR (url) {
      if (url) {
        linkToEasy('/pages/common/iframe?encode=1&url=' + encodeURIComponent(url))
      } else {
        error('暂无vr地址')
      }
    },
    // 全局ad跳转
    $redirectAd (adItem) {
      switch (adItem.type) {
        case 'tabbar':
          uni.redirectTo({
            url: adItem.image_url
          })
          break
        case 'web':
          uni.redirectTo({
            url: '/pages/common/iframe?url=' + adItem.image_url
          })
          break
        case 'page':
          linkToEasy(adItem.image_url)
          break
        default:
          error('未知类别')
          break
      }
    },
    /**
     * 全局AR扫描
     *
     */
    $arScan () {
      uni.chooseImage({
        success: function (res) {
          uni.getFileSystemManager().readFile({
            filePath: res.tempFilePaths[0], // 选择图片返回的相对路径
            encoding: 'base64', // 编码格式
            success: ret => { // 成功的回调
              var base64 = 'data:image/png;base64,' + ret.data
              arScanForflower({ file: base64 }).then(result => {
                const data = JSON.stringify(result.data)
                var path = '/pages/ar/flower?data1=' + data + '&data2=' + base64
                linkToEasy(path)
              }).catch(err => Exception.handle(err))
            }
          })
        }
      })
    },
    $qrScan () {
      // 允许从相机和相册扫码
      uni.scanCode({
        success (res) {
          // 所有二维码统一用链接来搞定
          // https://ad.qingclouds.cn/qr?channel=voice&scene=3185&item=6609304960
          // 这样就和微信直接扫码的规则一样
          var url = res.result
          // 用p参数模仿是从微信直接扫码的，我真聪明
          linkToEasy('/pages/common/qr?t=1&q=' + encodeURIComponent(url))
        }
      })
    },
    $getDomain: getDomain,
    $openLocation: openLocation,
    $cellPhone: cellPhone,
    $back: backFunc,
    $noop: () => {},
    $toast: toast,
    $error: error,
    $modal: modal,
    $linkTo: linkToEasy,
    $toGoodsDetail: toGoodsDetail,
    $checkIsLogin: checkIsLogin,
    $openPop (name) {
      this.$refs[name].show()
    },
    $closePop (name) {
      this.$refs[name].close()
    },
    // 批量注册变量名称
    $restLangueAssign (arr) {
      for (var name of arr) {
        this[name] = uni.T._(name)
      }
    },
    // 语言
    $t (line, data) {
      return uni.T._(line, data)
    },
    // 切换语种
    $setLocale (code) {
      uni.T.setLocale(code)
    },
    async default_init_func (options) {
      // 分享者
      const { from_mid = null } = options
      if (from_mid >= 0) {
        Storage.set('from_mid', from_mid)
      }
    },
    getCurrentPageRoute () {
      const pageInstanceList = getCurrentPages()
      const currentPagePath = pageInstanceList[pageInstanceList.length - 1].route
      return currentPagePath
    }
  },
  onShow () {
    // 这个机制还是要onShow 兼容返回的情况
    Storage.set('currentPagePath', this.getCurrentPageRoute())// 标记当前的页面，这样就不会每个事件都响应了
    this.currentPagePath = this.getCurrentPageRoute()
  },
  onReady () {

  },
  onLoad (options) {
    const opt = { ...options }
    // 这样简洁多了
    this.default_init_func(opt)
  },
  async created () {
    this.systemInfo = uni.getSystemInfoSync()
    // console.log('systemInfo', this.systemInfo)
    // #ifdef MP
    this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    const { height, top, left, bottom } = this.menuButtonInfo
    this.diyHeadHeight = bottom + 10
    this.diyHeadRight = this.systemInfo.windowWidth - left
    // #endif
    // #ifdef H5
    this.diyHeadHeight = 44
    this.menuButtonInfo = { height: 44 }
    // #endif
  },
  onShareAppMessage () {

  }

}

export const componetMixin = {
  data () {
    return {
      menuButtonInfo: {},
      systemInfo: {
        statusBarHeight: 0,
        windowHeight: 0
      },
      diyHeadHeight: 0,
      diyHeadRight: 0
    }
  },
  methods: {
    $getDomain: getDomain,
    $openLocation: openLocation,
    $cellPhone: cellPhone,
    $back: backFunc,
    $filterPrice: (price) => {
      return parseInt(Number(price) * 100) / 100
    },
    $noop: () => {},
    $toast: toast,
    $error: error,
    $modal: modal,
    $linkTo: linkToEasy,
    $toGoodsDetail: toGoodsDetail,
    $checkIsLogin: checkIsLogin,
    $openPop (name) {
      this.$refs[name].show()
    },
    $closePop (name) {
      this.$refs[name].close()
    }
  },
  created () {
    this.systemInfo = uni.getSystemInfoSync()

    // #ifdef MP-WEIXIN
    this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    const { height, top, left } = this.menuButtonInfo
    this.diyHeadHeight = top + height + (top - this.systemInfo.statusBarHeight) + 10
    this.diyHeadRight = this.systemInfo.windowWidth - left
    // #endif
    // #ifndef MP-WEIXIN
    this.diyHeadHeight = 54
    this.menuButtonInfo = { height: 44 }
    // #endif
  }
}
